home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / gzip.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  14KB  |  476 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. """Functions that read and write gzipped files.
  5.  
  6. The user of the file doesn't have to worry about the compression,
  7. but random access is not allowed."""
  8. import struct
  9. import sys
  10. import time
  11. import os
  12. import zlib
  13. import io
  14. import __builtin__
  15. __all__ = [
  16.     'GzipFile',
  17.     'open']
  18. (FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT) = (1, 2, 4, 8, 16)
  19. (READ, WRITE) = (1, 2)
  20.  
  21. def write32u(output, value):
  22.     output.write(struct.pack('<L', value))
  23.  
  24.  
  25. def read32(input):
  26.     return struct.unpack('<I', input.read(4))[0]
  27.  
  28.  
  29. def open(filename, mode = 'rb', compresslevel = 9):
  30.     """Shorthand for GzipFile(filename, mode, compresslevel).
  31.  
  32.     The filename argument is required; mode defaults to 'rb'
  33.     and compresslevel defaults to 9.
  34.  
  35.     """
  36.     return GzipFile(filename, mode, compresslevel)
  37.  
  38.  
  39. class GzipFile(io.BufferedIOBase):
  40.     '''The GzipFile class simulates most of the methods of a file object with
  41.     the exception of the readinto() and truncate() methods.
  42.  
  43.     '''
  44.     myfileobj = None
  45.     max_read_chunk = 10485760
  46.     
  47.     def __init__(self, filename = None, mode = None, compresslevel = 9, fileobj = None, mtime = None):
  48.         """Constructor for the GzipFile class.
  49.  
  50.         At least one of fileobj and filename must be given a
  51.         non-trivial value.
  52.  
  53.         The new class instance is based on fileobj, which can be a regular
  54.         file, a StringIO object, or any other object which simulates a file.
  55.         It defaults to None, in which case filename is opened to provide
  56.         a file object.
  57.  
  58.         When fileobj is not None, the filename argument is only used to be
  59.         included in the gzip file header, which may includes the original
  60.         filename of the uncompressed file.  It defaults to the filename of
  61.         fileobj, if discernible; otherwise, it defaults to the empty string,
  62.         and in this case the original filename is not included in the header.
  63.  
  64.         The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
  65.         depending on whether the file will be read or written.  The default
  66.         is the mode of fileobj if discernible; otherwise, the default is 'rb'.
  67.         Be aware that only the 'rb', 'ab', and 'wb' values should be used
  68.         for cross-platform portability.
  69.  
  70.         The compresslevel argument is an integer from 0 to 9 controlling the
  71.         level of compression; 1 is fastest and produces the least compression,
  72.         and 9 is slowest and produces the most compression. 0 is no compression
  73.         at all. The default is 9.
  74.  
  75.         The mtime argument is an optional numeric timestamp to be written
  76.         to the stream when compressing.  All gzip compressed streams
  77.         are required to contain a timestamp.  If omitted or None, the
  78.         current time is used.  This module ignores the timestamp when
  79.         decompressing; however, some programs, such as gunzip, make use
  80.         of it.  The format of the timestamp is the same as that of the
  81.         return value of time.time() and of the st_mtime member of the
  82.         object returned by os.stat().
  83.  
  84.         """
  85.         if mode:
  86.             mode = mode.replace('U', '')
  87.         if mode and 'b' not in mode:
  88.             mode += 'b'
  89.         if fileobj is None:
  90.             if not mode:
  91.                 pass
  92.             fileobj = self.myfileobj = __builtin__.open(filename, 'rb')
  93.         if filename is None:
  94.             if hasattr(fileobj, 'name') and fileobj.name != '<fdopen>':
  95.                 filename = fileobj.name
  96.             else:
  97.                 filename = ''
  98.         if mode is None:
  99.             if hasattr(fileobj, 'mode'):
  100.                 mode = fileobj.mode
  101.             else:
  102.                 mode = 'rb'
  103.         if mode[0:1] == 'r':
  104.             self.mode = READ
  105.             self._new_member = True
  106.             self.extrabuf = ''
  107.             self.extrasize = 0
  108.             self.extrastart = 0
  109.             self.name = filename
  110.             self.min_readsize = 100
  111.         elif mode[0:1] == 'w' or mode[0:1] == 'a':
  112.             self.mode = WRITE
  113.             self._init_write(filename)
  114.             self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, -(zlib.MAX_WBITS), zlib.DEF_MEM_LEVEL, 0)
  115.         else:
  116.             raise IOError, 'Mode ' + mode + ' not supported'
  117.         self.fileobj = None
  118.         self.offset = 0
  119.         self.mtime = mtime
  120.         if self.mode == WRITE:
  121.             self._write_gzip_header()
  122.  
  123.     
  124.     def filename(self):
  125.         import warnings as warnings
  126.         warnings.warn('use the name attribute', DeprecationWarning, 2)
  127.         if self.mode == WRITE and self.name[-3:] != '.gz':
  128.             return self.name + '.gz'
  129.         return None.name
  130.  
  131.     filename = property(filename)
  132.     
  133.     def __repr__(self):
  134.         s = repr(self.fileobj)
  135.         return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  136.  
  137.     
  138.     def _check_closed(self):
  139.         '''Raises a ValueError if the underlying file object has been closed.
  140.  
  141.         '''
  142.         if self.closed:
  143.             raise ValueError('I/O operation on closed file.')
  144.  
  145.     
  146.     def _init_write(self, filename):
  147.         self.name = filename
  148.         self.crc = zlib.crc32('') & 0xFFFFFFFFL
  149.         self.size = 0
  150.         self.writebuf = []
  151.         self.bufsize = 0
  152.  
  153.     
  154.     def _write_gzip_header(self):
  155.         self.fileobj.write('\x1f\x8b')
  156.         self.fileobj.write('\x08')
  157.         fname = os.path.basename(self.name)
  158.         if fname.endswith('.gz'):
  159.             fname = fname[:-3]
  160.         flags = 0
  161.         if fname:
  162.             flags = FNAME
  163.         self.fileobj.write(chr(flags))
  164.         mtime = self.mtime
  165.         if mtime is None:
  166.             mtime = time.time()
  167.         write32u(self.fileobj, long(mtime))
  168.         self.fileobj.write('\x02')
  169.         self.fileobj.write('\xff')
  170.         if fname:
  171.             self.fileobj.write(fname + '\x00')
  172.  
  173.     
  174.     def _init_read(self):
  175.         self.crc = zlib.crc32('') & 0xFFFFFFFFL
  176.         self.size = 0
  177.  
  178.     
  179.     def _read_gzip_header(self):
  180.         magic = self.fileobj.read(2)
  181.         if magic != '\x1f\x8b':
  182.             raise IOError, 'Not a gzipped file'
  183.         method = ord(self.fileobj.read(1))
  184.         if method != 8:
  185.             raise IOError, 'Unknown compression method'
  186.         flag = ord(self.fileobj.read(1))
  187.         self.mtime = read32(self.fileobj)
  188.         self.fileobj.read(2)
  189.         if flag & FEXTRA:
  190.             xlen = ord(self.fileobj.read(1))
  191.             xlen = xlen + 256 * ord(self.fileobj.read(1))
  192.             self.fileobj.read(xlen)
  193.         if flag & FNAME:
  194.             while True:
  195.                 s = self.fileobj.read(1)
  196.                 if not not s:
  197.                     if s == '\x00':
  198.                         break
  199.                         continue
  200.                 if flag & FCOMMENT:
  201.                     while True:
  202.                         s = self.fileobj.read(1)
  203.                         if not not s:
  204.                             if s == '\x00':
  205.                                 break
  206.                                 continue
  207.                         if flag & FHCRC:
  208.                             self.fileobj.read(2)
  209.                         return None
  210.  
  211.     
  212.     def write(self, data):
  213.         self._check_closed()
  214.         if self.mode != WRITE:
  215.             import errno as errno
  216.             raise IOError(errno.EBADF, 'write() on read-only GzipFile object')
  217.         if self.fileobj is None:
  218.             raise ValueError, 'write() on closed GzipFile object'
  219.         if isinstance(data, memoryview):
  220.             data = data.tobytes()
  221.         if len(data) > 0:
  222.             self.size = self.size + len(data)
  223.             self.crc = zlib.crc32(data, self.crc) & 0xFFFFFFFFL
  224.             self.fileobj.write(self.compress.compress(data))
  225.             self.offset += len(data)
  226.         return len(data)
  227.  
  228.     
  229.     def read(self, size = -1):
  230.         self._check_closed()
  231.         if self.mode != READ:
  232.             import errno
  233.             raise IOError(errno.EBADF, 'read() on write-only GzipFile object')
  234.         if self.extrasize <= 0 and self.fileobj is None:
  235.             return ''
  236.         readsize = None
  237.         if size < 0:
  238.             
  239.             try:
  240.                 while True:
  241.                     self._read(readsize)
  242.                     readsize = min(self.max_read_chunk, readsize * 2)
  243.             except EOFError:
  244.                 size = self.extrasize
  245.             
  246.  
  247.         
  248.         try:
  249.             while size > self.extrasize:
  250.                 self._read(readsize)
  251.                 readsize = min(self.max_read_chunk, readsize * 2)
  252.         except EOFError:
  253.             if size > self.extrasize:
  254.                 size = self.extrasize
  255.             
  256.  
  257.         offset = self.offset - self.extrastart
  258.         chunk = self.extrabuf[offset:offset + size]
  259.         self.extrasize = self.extrasize - size
  260.         self.offset += size
  261.         return chunk
  262.  
  263.     
  264.     def _unread(self, buf):
  265.         self.extrasize = len(buf) + self.extrasize
  266.         self.offset -= len(buf)
  267.  
  268.     
  269.     def _read(self, size = 1024):
  270.         if self.fileobj is None:
  271.             raise EOFError, 'Reached EOF'
  272.         if self._new_member:
  273.             pos = self.fileobj.tell()
  274.             self.fileobj.seek(0, 2)
  275.             if pos == self.fileobj.tell():
  276.                 raise EOFError, 'Reached EOF'
  277.             self.fileobj.seek(pos)
  278.             self._init_read()
  279.             self._read_gzip_header()
  280.             self.decompress = zlib.decompressobj(-(zlib.MAX_WBITS))
  281.             self._new_member = False
  282.         buf = self.fileobj.read(size)
  283.         if buf == '':
  284.             uncompress = self.decompress.flush()
  285.             self._read_eof()
  286.             self._add_read_data(uncompress)
  287.             raise EOFError, 'Reached EOF'
  288.         uncompress = self.decompress.decompress(buf)
  289.         self._add_read_data(uncompress)
  290.         if self.decompress.unused_data != '':
  291.             self.fileobj.seek(-len(self.decompress.unused_data) + 8, 1)
  292.             self._read_eof()
  293.             self._new_member = True
  294.  
  295.     
  296.     def _add_read_data(self, data):
  297.         self.crc = zlib.crc32(data, self.crc) & 0xFFFFFFFFL
  298.         offset = self.offset - self.extrastart
  299.         self.extrabuf = self.extrabuf[offset:] + data
  300.         self.extrasize = self.extrasize + len(data)
  301.         self.extrastart = self.offset
  302.         self.size = self.size + len(data)
  303.  
  304.     
  305.     def _read_eof(self):
  306.         self.fileobj.seek(-8, 1)
  307.         crc32 = read32(self.fileobj)
  308.         isize = read32(self.fileobj)
  309.         if crc32 != self.crc:
  310.             raise IOError('CRC check failed %s != %s' % (hex(crc32), hex(self.crc)))
  311.         if isize != self.size & 0xFFFFFFFFL:
  312.             raise IOError, 'Incorrect length of data produced'
  313.         c = '\x00'
  314.         while c == '\x00':
  315.             c = self.fileobj.read(1)
  316.         if c:
  317.             self.fileobj.seek(-1, 1)
  318.  
  319.     
  320.     def closed(self):
  321.         return self.fileobj is None
  322.  
  323.     closed = property(closed)
  324.     
  325.     def close(self):
  326.         if self.fileobj is None:
  327.             return None
  328.         if None.mode == WRITE:
  329.             self.fileobj.write(self.compress.flush())
  330.             write32u(self.fileobj, self.crc)
  331.             write32u(self.fileobj, self.size & 0xFFFFFFFFL)
  332.             self.fileobj = None
  333.         elif self.mode == READ:
  334.             self.fileobj = None
  335.         if self.myfileobj:
  336.             self.myfileobj.close()
  337.             self.myfileobj = None
  338.  
  339.     
  340.     def flush(self, zlib_mode = zlib.Z_SYNC_FLUSH):
  341.         self._check_closed()
  342.         if self.mode == WRITE:
  343.             self.fileobj.write(self.compress.flush(zlib_mode))
  344.             self.fileobj.flush()
  345.  
  346.     
  347.     def fileno(self):
  348.         """Invoke the underlying file object's fileno() method.
  349.  
  350.         This will raise AttributeError if the underlying file object
  351.         doesn't support fileno().
  352.         """
  353.         return self.fileobj.fileno()
  354.  
  355.     
  356.     def rewind(self):
  357.         '''Return the uncompressed stream file position indicator to the
  358.         beginning of the file'''
  359.         if self.mode != READ:
  360.             raise IOError("Can't rewind in write mode")
  361.         self.fileobj.seek(0)
  362.         self._new_member = True
  363.         self.extrabuf = ''
  364.         self.extrasize = 0
  365.         self.extrastart = 0
  366.         self.offset = 0
  367.  
  368.     
  369.     def readable(self):
  370.         return self.mode == READ
  371.  
  372.     
  373.     def writable(self):
  374.         return self.mode == WRITE
  375.  
  376.     
  377.     def seekable(self):
  378.         return True
  379.  
  380.     
  381.     def seek(self, offset, whence = 0):
  382.         if whence:
  383.             if whence == 1:
  384.                 offset = self.offset + offset
  385.             else:
  386.                 raise ValueError('Seek from end not supported')
  387.         if self.mode == WRITE:
  388.             if offset < self.offset:
  389.                 raise IOError('Negative seek in write mode')
  390.             count = offset - self.offset
  391.             for i in xrange(count // 1024):
  392.                 self.write(1024 * '\x00')
  393.             
  394.             self.write((count % 1024) * '\x00')
  395.         elif self.mode == READ:
  396.             if offset < self.offset:
  397.                 self.rewind()
  398.             count = offset - self.offset
  399.             for i in xrange(count // 1024):
  400.                 self.read(1024)
  401.             
  402.             self.read(count % 1024)
  403.         return self.offset
  404.  
  405.     
  406.     def readline(self, size = -1):
  407.         if size < 0:
  408.             offset = self.offset - self.extrastart
  409.             i = self.extrabuf.find('\n', offset) + 1
  410.             if i > 0:
  411.                 self.extrasize -= i - offset
  412.                 self.offset += i - offset
  413.                 return self.extrabuf[offset:i]
  414.             size = None.maxint
  415.             readsize = self.min_readsize
  416.         else:
  417.             readsize = size
  418.         bufs = []
  419.         while size != 0:
  420.             c = self.read(readsize)
  421.             i = c.find('\n')
  422.             if (size <= i or i == -1) and len(c) > size:
  423.                 i = size - 1
  424.             if i >= 0 or c == '':
  425.                 bufs.append(c[:i + 1])
  426.                 self._unread(c[i + 1:])
  427.                 break
  428.             bufs.append(c)
  429.             size = size - len(c)
  430.             readsize = min(size, readsize * 2)
  431.         if readsize > self.min_readsize:
  432.             self.min_readsize = min(readsize, self.min_readsize * 2, 512)
  433.         return ''.join(bufs)
  434.  
  435.  
  436.  
  437. def _test():
  438.     args = sys.argv[1:]
  439.     if args:
  440.         pass
  441.     decompress = args[0] == '-d'
  442.     if decompress:
  443.         args = args[1:]
  444.     if not args:
  445.         args = [
  446.             '-']
  447.     for arg in args:
  448.         if decompress:
  449.             if arg == '-':
  450.                 f = GzipFile(filename = '', mode = 'rb', fileobj = sys.stdin)
  451.                 g = sys.stdout
  452.             elif arg[-3:] != '.gz':
  453.                 print "filename doesn't end in .gz:", repr(arg)
  454.                 continue
  455.             f = open(arg, 'rb')
  456.             g = __builtin__.open(arg[:-3], 'wb')
  457.         elif arg == '-':
  458.             f = sys.stdin
  459.             g = GzipFile(filename = '', mode = 'wb', fileobj = sys.stdout)
  460.         else:
  461.             f = __builtin__.open(arg, 'rb')
  462.             g = open(arg + '.gz', 'wb')
  463.         while True:
  464.             chunk = f.read(1024)
  465.             if not chunk:
  466.                 break
  467.             g.write(chunk)
  468.         if g is not sys.stdout:
  469.             g.close()
  470.         if f is not sys.stdin:
  471.             f.close()
  472.             continue
  473.  
  474. if __name__ == '__main__':
  475.     _test()
  476.